package com.dragonboat.service;
import com.dragonboat.entity.Audience;
import com.dragonboat.util.PasswordUtil;
import com.dragonboat.entity.Event;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dragonboat.entity.Audience;
import com.dragonboat.repository.AudienceRepository;
import com.dragonboat.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
@Service
@Transactional
public class AudienceService {
    @Autowired
    private CommonService commonService;
    @Autowired
    private AudienceRepository audienceRepository;

    public ResponseResult<Audience> register(String audienceName, String password) {
        if (audienceRepository.existsByAudienceName(audienceName)) {
            return ResponseResult.error("用户名已存在");
        }

        Audience audience = new Audience();
        audience.setAudienceName(audienceName);
        audience.setPassword(password);


        audienceRepository.save(audience);
        audience.setPassword(null); // 不返回密码

        return ResponseResult.success(audience);
    }


    public List<Event> getUpcomingEvents() {
        return commonService.getUpcomingEvents();
    }

    public Optional<Audience> login(Integer audienceId, String password) {
        return audienceRepository.findById(audienceId)
                .filter(a -> PasswordUtil.matches(password, a.getPassword()));
    }
    public Optional<Audience> loginByName(String audienceName, String password) {
        return audienceRepository.findByAudienceName(audienceName)
                .filter(a -> PasswordUtil.matches(password, a.getPassword()));
    }
    public Audience updateAudienceInfo(Integer audienceId, String name, String newPassword) {
        return audienceRepository.findById(audienceId).map(audience -> {
            if (name != null && !name.isEmpty()) audience.setAudienceName(name);
            if (newPassword != null && !newPassword.isEmpty()) {
                // 注意：这里接收的已经是加密后的密码
                audience.setPassword(newPassword);
            }
            return audienceRepository.save(audience);
        }).orElse(null);
    }
    public Audience getAudienceById(Integer audienceId) {
        return audienceRepository.findById(audienceId).orElse(null);
    }
    public Optional<Audience> findById(Integer audienceId) {
        return audienceRepository.findById(audienceId);
    }
    public Optional<Event> getEventDetails(Integer eventId) {
        return commonService.getEventById(eventId);
    }
}